$(function(){

/*************************** find out coordinates for the route according to how the radius is set	 ***************************************/			 	
	 	var directionsDisplay;
		var directionsService = new google.maps.DirectionsService();
		var map;
		
	$.getJSON("js/categories.json", function(data){
 	
	 	var cafe = data.categorycafe;
	 	var spa = data.categoryspa;
	 	var totCat = [];
		var objectArray = [];
		
		var pathSteps = [];  //Array for storing all of the retrieved points from direction response 
		var desiredSteps = []; //global array
		var radius = 5000;
		
		
/*************************** concatenate all categories to one long array of objects	 ***************************************/		
	
	 	totCat = spa.concat(cafe);

		for(var i in totCat)
		{
			totCat[i].id = i;
		};
		
/*************************** Calculating the distance between two points ***************************************/		

		computeDistance = function(point1, point2) {
 			var distance = google.maps.geometry.spherical.computeDistanceBetween(point1, point2);
 		return distance;
		};					


		function initialize() {
		  directionsDisplay = new google.maps.DirectionsRenderer();
	    var stockholm = new google.maps.LatLng( 59.32536, 18.071197);
		  var myOptions = {
		    zoom:7,
		    mapTypeId: google.maps.MapTypeId.ROADMAP,
		    center: stockholm
		  	}
		  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
 			directionsDisplay.setMap(map);
			}

		function calcRoute() {
			var stockholm = new google.maps.LatLng( 59.333333, 18.05);
			var uppsala = new google.maps.LatLng( 59.85, 17.633333);
 			var request = {
	    	origin:stockholm, //"Stockholm, SV",
    		destination:uppsala, //"Uppsala, SV",
    		travelMode: google.maps.TravelMode.DRIVING
  			};
  		directionsService.route(request, function(result, status) {
    	if (status == google.maps.DirectionsStatus.OK) {
      	directionsDisplay.setDirections(result);
      	desiredSteps[0]=stockholm; // Add Start
   	
      	
          pathSteps = result.routes[0].overview_path;
   				var tempDistance = 0; 	//This variable is used to sum the distance between a certain step and the steps that follow,
                      				   	//It is reset as long as the summed distance become more than the distance from route (radius)*2 - 500
 					desiredSteps.push(pathSteps[0]);
				  for (var i = 0; i < pathSteps.length-1; i++){
				    tempDistance += computeDistance(pathSteps[i], pathSteps[i+1]);
			   		if (tempDistance > 2*radius-500) {
					    desiredSteps.push(pathSteps[i]);
					    tempDistance = 0;
					    }; 
	  				};
 				desiredSteps.push(uppsala); // Add Stop
  				  				
				
/****************************************************** place markers for desiredSteps	 **********************************************************/			 	

desiredSteps.unshift();

/****************************** loop through to check which toppstopps are at a certain step **************************************************/			 	

var sortedTotCat = [];
var sortedCount = 0;

for (var i=0; i <= (desiredSteps.length-1); i++) { // Outer loop 
	var tmpArray = [];
	var count = 0;
	
	if (i != desiredSteps.length-1) {	// this check is done because last step use the same radius as the previous
		var stepDistance = computeDistance( desiredSteps[i], desiredSteps[i+1] );
	};
	
	for (var y=0; y <= totCat.length-1; y++){ //Inner loop
	
		var distance = CalcDistanceBetween( desiredSteps[i].Ja, desiredSteps[i].Ka, totCat[y].lat, totCat[y].long );
		
		if (distance < stepDistance && totCat[y].found == 0) {
			tmpArray[count] = {dist:distance, id:totCat[y].id, index:y, obj:totCat[y]}; 
			count += 1;
		};
	};

/*************************** sorting tmpArray so that for every desired step, toppstopps come in ascending order  ******************************/			 	
	function sorttmpArray(a,b) {
    	var x = a.dist;
    	var y = b.dist;
		return x - y;
	};
	tmpArray.sort(sorttmpArray);

/****************************** moving elements to new sorted array and mark them up as found **********************************************/			 	
	
	for (var p=0; p <= tmpArray.length-1; p++) {
	
/**************************** moving …..  *********************************/			 	
	
		sortedTotCat[sortedCount] = tmpArray[p].obj;
		sortedCount += 1;
		

/*************************** and mark as found  ….. ******************************/			 	
		var positionFound = tmpArray[p].index;		
	
		totCat[positionFound].found ="1"; 

		};	
};

/*************************** make array of objects 	 ***************************************/			 		 	
	
		 	for(var counter=0; counter <= sortedTotCat.length-1; counter++)	{
				objectArray[counter] = new listRow(
				counter,
				sortedTotCat[counter].rid,
				sortedTotCat[counter].cid,
				sortedTotCat[counter].lat,
				sortedTotCat[counter].long,
				sortedTotCat[counter].name,
				sortedTotCat[counter].adress,
				sortedTotCat[counter].phone
				);
			};

		
						
				
/*******************************************************************************************/				
    		};
  		});  		
		};
		
		initialize();
		calcRoute();	

	});


/************************************************************************************
 *																																									*
 *		Objekt som håller i info för varje rad																				*
 *																																									*
 ************************************************************************************
*/


			function listRow(index,rid,cid,lat,long,name,address,phone) {
			
			var marker;
				// init vars

				var categorySymbolArray = ["","C", "S"];
				var categoryColorArray = ["","#85BED9", "#98693B"];
				var categoryMarkerImage = [	"","images/markers/spa-marker.png",
										"images/markers/cafe-marker.png"];
										
				// Bygga upp HTML-elementen i en rad

					var categoryColorHTML = categoryColorArray[cid];				
					var rowHTML = $("<div class='listrow' id='"+index+"' ></div>");
					var nameHTML = $("<div class='name' >"+name+"</div>");
					var categorySymbolHTML = $("<div class='catSymbol' >"+categorySymbolArray[cid]+"</div>");


				// Merging together the whole row
				rowHTML.append(categorySymbolHTML).append(nameHTML).css("color",categoryColorHTML);
								
				
				// Append row to page			 			
				 $("#leftcontrols").append(rowHTML); 

			


/********************************* put out marker **************************************************/

			var image = new google.maps.MarkerImage(categoryMarkerImage[cid], 
			      // This marker is 20 pixels wide by 32 pixels tall. 
			      new google.maps.Size(28, 38),
			      // The origin for this image is 0,0.
			      new google.maps.Point(0,0),
			      // The anchor for this image is the base of the flagpole at 0,32.
			      new google.maps.Point(14, 38));
      	
			var location = new google.maps.LatLng(lat,long); 
			marker = new google.maps.Marker(
				{
		  	   	position: location, 
		  	   	map: map,
		  	   	icon: image
		  		});		  	

			
/********************************* bind events **************************************************/
				 
		 	google.maps.event.addListener(marker, 'mouseover', function() {
		 		indexHTML=index+""	;
    			$("#"+index).css("background",categoryColorArray[cid]).css( "color","black");
    			});				 
				 
		 	google.maps.event.addListener(marker, 'mouseout', function() {
		 		indexHTML=index+""	;
    			$("#"+index).css("background","rgb(25,25,25)").css("color",categoryColorArray[cid]);
    			});				 

			$("#"+index).mouseenter(function(){
				
				var image = new google.maps.MarkerImage('images/markers/restaurant-marker.png', 
			      // This marker is 20 pixels wide by 32 pixels tall. 
			      new google.maps.Size(28, 38),
			      // The origin for this image is 0,0.
			      new google.maps.Point(0,0),
			      // The anchor for this image is the base of the flagpole at 0,32.
			      new google.maps.Point(14, 38));
      	
				var location = new google.maps.LatLng(lat,long); 
				var marker = new google.maps.Marker(
					{
		  	   		position: location, 
		  	   		map: map,
		  	   		icon: image
		  			});
		  			
			 	google.maps.event.addListener(marker, 'mouseover', function() {
			 		indexHTML=index+""	;
	    			$("#"+index).css("background",categoryColorArray[cid]).css( "color","black");
	    			});				 
					 
			 	google.maps.event.addListener(marker, 'mouseout', function() {
			 		indexHTML=index+""	;
	    			$("#"+index).css("background","rgb(25,25,25)").css("color",categoryColorArray[cid]);
	    			});				 
	
		  					  	
				});				 
				 
			$("#"+index).mouseleave(function(){
				
				var image = new google.maps.MarkerImage(categoryMarkerImage[cid], 
			      // This marker is 20 pixels wide by 32 pixels tall. 
			      new google.maps.Size(28, 38),
			      // The origin for this image is 0,0.
			      new google.maps.Point(0,0),
			      // The anchor for this image is the base of the flagpole at 0,32.
			      new google.maps.Point(14, 38));
      	
				var location = new google.maps.LatLng(lat,long); 
				var marker = new google.maps.Marker(
					{
		  	   		position: location, 
		  	   		map: map,
		  	   		icon: image
		  			});	
		  			
			 	google.maps.event.addListener(marker, 'mouseover', function() {
			 		indexHTML=index+""	;
	    			$("#"+index).css("background",categoryColorArray[cid]).css( "color","black");
	    			});				 
					 
			 	google.maps.event.addListener(marker, 'mouseout', function() {
			 		indexHTML=index+""	;
	    			$("#"+index).css("background","rgb(25,25,25)").css("color",categoryColorArray[cid]);
	    			});				 
		  				  	
				});				 
				 
				$("#"+index).click(function () {
					marker.setMap(null);
				
				}); 
				 

/************************************************************************************
 *					 setters														
 ************************************************************************************
*/

				function setindex( newIndx ){
		 			index = newIndx;
		 		};
				function setrecordid( newRid ){
		 			rid = newRid;
		 		};
				function setcategoryid( newCid ){
		 			cid = newCid;
		 		};
				function setlongitude( newLong ){
		 			long = newLong;
		 		};
				function setlatitude( newLat ){
		 			lat = newLat;
		 		};
				function setname( newName ){
		 			name = newName;
		 		};
				function setaddress( newAdr ){
		 			address = newAdr;
		 		};
				function setphone( newPhone ){
		 			phone = newPhone;
		 		};

		 		
			
/************************************************************************************
 *					 getters													
 ************************************************************************************
*/
				function getindex(){
		 			return index;
		 		};
				function getrecordid(){
		 			return rid;
		 		};
				function getcategoryid(){
		 			return cid;
		 		};							
				function getlongitude() {
		 			return long;
		 		};
		 		function getlatitude(){
		 			return lat;
		 		};		 		
				function getname() {
		 			return name;
		 		};		 		
				function getaddress() {
		 			return address;
		 		};
		 		function getphone() {
		 			return phone;
		 		};
		 		
		 		// returns
				return {
					setindex: setindex,
					getindex: getindex,
					setrecordid: setrecordid,
					getrecordid: getrecordid,
					setcategoryid: setcategoryid,
					getcategoryid: getcategoryid,					
					setlatitude: setlatitude,
		 		 	getlatitude: getlatitude,
					setlongitude: setlongitude,
		 		 	getlongitude: getlongitude,
					setname: setname,
		 		 	getname: getname,		 		 	
					setaddress: setaddress,
		 		 	getaddress: getaddress,		 		 	
					setphone: setphone,
		 		 	getphone: getphone,
				};
			
			};
			
		

});

